package com.leyou.interceptor;


import com.alibaba.fastjson.JSON;
import com.leyou.common.pojo.UserLogin;
import com.leyou.common.utils.token.JwtUtils;
import com.leyou.common.utils.token.RasUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static com.leyou.common.utils.token.RasUtils.publicKeyPath;

/**
 * @author xhh
 * @date 2022/3/10
 */
@Slf4j
@Component
public class TokenIntercepter implements HandlerInterceptor {
    //过滤的
    private String[] urls={
            "/management-personnel/login/managerLogin",
            "/management-personnel/login/testHttpRequest",
    };

    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String method=request.getMethod();
        if(method.equals("OPTIONS")) {

            System.out.println("啥东西啊");

        }
        String url=request.getRequestURI();
        String token=request.getHeader("token");

        for(String item:urls){
            if(url.equals(item)){
                return true;
            }
        }
        UserLogin objectFromToken=null;
        try {
            objectFromToken= JwtUtils.getObjectFromToken(token, RasUtils.getPublicKey(publicKeyPath), UserLogin.class);
            System.out.println(objectFromToken);
            if(objectFromToken==null){
                return false;
            }
            else {
                request.setAttribute("managerAccountNumber",objectFromToken.getManagerAccountNumber());
                return true;
            }
        }catch (ExpiredJwtException exception){
            log.info("登录超时了");
            PrintWriter writer=null;
            try {
                writer = response.getWriter();
                Map map=new HashMap(8);
                map.put("code","403.1");
                String string = JSON.toJSONString(map);
                writer.write(string);
                writer.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(writer!=null){
                    writer.close();
                }
            }
            return false;
        }catch (Exception exception){
            exception.printStackTrace();
            return false;
        }

    }
}
